In Svelte, the onMount function is a lifecycle hook that runs after the component has been mounted to the DOM. It is commonly used to run code that requires access to the DOM or to perform side effects such as fetching data from an API.
Fetching data from a server when a component loads.
Subscribing to services or starting timers.
Running code that interacts with the DOM.
Initializing third-party libraries that need a mounted DOM element.
In this example, the onMount function is used to simulate fetching data. The code inside it runs only once, right after the component is first added to the DOM.
onMount ensures that the fetch call only runs once after the component is rendered.
onMount runs only once when the component is first mounted.
It is perfect for initialization logic like data fetching or DOM manipulation.
The function passed to onMount can be asynchronous.
If you return a cleanup function, it will run when the component is destroyed (similar to componentWillUnmount in React).